#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:从字典中提取子集
问题: 你想构造一个字典，它是另外一个字典的子集
提示 : 
    1. 字典推导方式表意更清晰，并且实际上也会运行的更快些
"""
prices = {
    'ACME': 45.23,
    'AAPL': 612.78,
    'IBM': 205.55,
    'HPQ': 37.20,
    'FB': 10.75
}
print(f"{prices = }")

def recipe1():
    """最简单的方式是使用字典推导"""
    p1 = {key: value for key, value in prices.items() if value > 200}
    print(f"{p1 = }")

    tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'}
    p2 = {key: value for key, value in prices.items() if key in tech_names}
    print(f"{p2 = }")
    # 另种写法，比上一种方案慢 1.6 倍
    p3 = {key: prices[key] for key in prices.keys() & tech_names}
    print(f"{p3 = }")

def recipe2():
    """创建一个元组序列然后把它传给 dict() 函数"""
    p1 = dict((key, value) for key, value in prices.items() if value > 200)
    print(f"{p1 = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1() 
    print('recipe2'.center(20, '*'))
    recipe2() 

if __name__ == '__main__':
    main()    